//
//  SEConfirmReserveViewController.swift
//  SmartEyeForPatient
//
//  Created by QDSG on 2021/4/7.
//

import UIKit

enum SEConfirmReserveViewControllerFromType {
    case hospitalizeOrderList
    case hospitalizeReserve
}

class SEConfirmReserveViewController: SEBaseViewController {
    
    private var viewModel = SEHospitalizeOrderDetailViewModel()

    var paySuccessHandler: (() -> Void)?
    
    convenience init(inquiryId: String, fromType: SEConfirmReserveViewControllerFromType) {
        self.init()
        self.viewModel.model.id = inquiryId
        self.viewModel.fromType = fromType
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        loadData()
        
        viewModel.updateData = { [weak self] status in
            switch status {
            case .success:
                self?.tableView.isHidden = false
                self?.payView.isHidden = false
                self?.tableView.reloadData()
                self?.payView.updateView(with: self?.viewModel.payViewModel ?? SEConfirmReservePayViewModel())
            case .auth:
                self?.presentLoginViewController(selector: #selector(self?.loadData))
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }

        viewModel.payHandler = { [weak self] status in
            switch status {
            case .success:
                self?.paySuccess()
            case .auth:
                self?.presentLoginViewController(selector: #selector(self?.requestPayHospitalize))
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }
    }
    
    @IBOutlet private weak var payView: SEConfirmReservePayView! {
        didSet {
            payView.isHidden = true
            payView.delegate = self
        }
    }

    @IBOutlet private weak var tableView: UITableView! {
        didSet {
            tableView.isHidden = true
            tableView.backgroundColor = .background
            tableView.tableFooterView = UIView()
            tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 0)
            
            tableView.register(SEConfirmReserveDoctorInfoCell.nibForCell(),
                               forCellReuseIdentifier: SEConfirmReserveDoctorInfoCell.reuseIdentifier())
            tableView.register(SEConfirmReserveInfoCell.nibForCell(),
                               forCellReuseIdentifier: SEConfirmReserveInfoCell.reuseIdentifier())
            tableView.register(SEConfirmReserveImageCell.nibForCell(),
                               forCellReuseIdentifier: SEConfirmReserveImageCell.reuseIdentifier())
            tableView.register(SEConfirmReservePatientCell.nibForCell(),
                               forCellReuseIdentifier: SEConfirmReservePatientCell.reuseIdentifier())
        }
    }

    private func pushToChat() {
        let model = SEInquiryInfo(type: .online, id: viewModel.model.id)
        let vm = SEInquiryInfoViewModel(info: model)
        let vc = SEChatViewController(infoViewModel: vm)
        vc.title = viewModel.model.doctorName
        removeCurrentVcWhenPush(vc)
    }

    private func paySuccess() {
        switch viewModel.fromType {
        case .hospitalizeOrderList:
            SEHUD.show(message: "支付成功")
            self.paySuccessHandler?()
            navigationController?.popViewController(animated: true)
        case .hospitalizeReserve:
            pushToChat()
        }
    }
}

// MARK: - APIRequest

extension SEConfirmReserveViewController {
    @objc private func loadData() {
        viewModel.requestHospitalizeOrderDetail()
    }

    @objc private func requestPayHospitalize() {
        viewModel.requestPayHospitalize()
    }
}

// MARK: - SEConfirmReservePayViewDelegate

extension SEConfirmReserveViewController: SEConfirmReservePayViewDelegate {
    func confirmReservePayViewBtnAction(_ payView: SEConfirmReservePayView, with actionType: SEConfirmReservePayViewActionType) {
        switch actionType {
        case .pay:
            requestPayHospitalize()
        case .agree:
            viewModel.isAgree = payView.agreeBtn.isSelected
        case .showInfo:
            showAgreementView()
        }
    }

    private func showAgreementView() {
        let agreementView = UINib.loadViewFrom(AgreementAlertView.self)
                        agreementView.show(type: .informedLetter)
    }
}

// MARK: - UITableViewDataSource

extension SEConfirmReserveViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0, 2: return 1
        case 1: return 4
        default: return 0
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
        case 0:
            let cell = tableView.dequeueReusableCell(withIdentifier: SEConfirmReserveDoctorInfoCell.reuseIdentifier()) as! SEConfirmReserveDoctorInfoCell
            cell.update(with: viewModel)
            return cell
        case 1:
            if indexPath.row == 3 {
                let cell = tableView.dequeueReusableCell(withIdentifier: SEConfirmReserveImageCell.reuseIdentifier(), for: indexPath) as! SEConfirmReserveImageCell
                cell.updateWithViewModel(viewModel)
                return cell
            }
            
            let cell = tableView.dequeueReusableCell(withIdentifier: SEConfirmReserveInfoCell.reuseIdentifier(), for: indexPath) as! SEConfirmReserveInfoCell
            cell.updateWithViewModel(viewModel, atIndexPath: indexPath)
            return cell
        case 2:
            let cell = tableView.dequeueReusableCell(withIdentifier: SEConfirmReservePatientCell.reuseIdentifier()) as! SEConfirmReservePatientCell
            cell.updateWithViewModel(viewModel)
            return cell
        default:
            return UITableViewCell()
        }
    }
}

// MARK: - UITableViewDelegate

extension SEConfirmReserveViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        switch section {
        case 1:
            let header = UINib.loadViewFrom(SEDottedLineCornerView.self)
            return header
        case 2:
            let header = UINib.loadViewFrom(SEDottedLineView.self)
            return header
        default:
            return UIView()
        }
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return (section == 1 || section == 2) ? 20 : 10
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }
}
